#include "savecurvedata.h"
#include <QDebug>
#include <QMessageBox>
#include "curve.h"

SaveCurveData::SaveCurveData(Curve &curve, QObject *parent)
    : QObject(parent)
    , m_curve(&curve)
{
    m_timer = new QTimer(this);
    connect(m_timer, &QTimer::timeout, this, &SaveCurveData::onTimeout);
}

SaveCurveData::~SaveCurveData()
{

}

void SaveCurveData::setPeriod(int period)
{
    m_period = period;
}

int SaveCurveData::getPeriod()
{
    return m_period;
}

void SaveCurveData::setFileName(const QString &fileName)
{
    m_fileName = fileName;
}

QString SaveCurveData::getFileName()
{
    return m_fileName;
}

void SaveCurveData::addData(const QString &data)
{
    m_datas << data;
}

void SaveCurveData::addData(const QList<QString> &data)
{
    m_datas << data;
}

void SaveCurveData::start()
{
    if (m_timer->isActive())
        return;

    m_file.setFileName(m_fileName);
    m_file.open(QIODevice::WriteOnly);
    if (!m_file.isOpen())
    {
        QMessageBox::warning(nullptr, tr("Warning"), tr("The file %1 can not open!").arg(m_fileName));
        return;
    }

    QCustomPlot &cp = m_curve->getQCustomPlot();
    QString line;
    // 第一行记录图表名称
    line.clear();
    line.append("Name : ");
    line.append(m_curve->getTitle());
    line.append("\n");
    m_file.write(line.toLatin1());

    // 第2行记录日期时间
    line.clear();
    line.append("DateTime : ");
    QString dateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    line.append(dateTime);
    line.append("\n");
    m_file.write(line.toLatin1());

    // 第3行记录x轴信息
    line.clear();
    line.append("X axis label : ");
    line.append(cp.xAxis->label());
    line.append("\n");
    m_file.write(line.toLatin1());

    // 第4行记录序号和曲线名称
    line.clear();
    line.append("index");
    for (int j = 0; j < cp.graphCount(); j++)
    {
        line.append(" ");
        line.append(cp.graph(j)->name());
    }
    line.append("\n");
    m_file.write(line.toLatin1());
    m_file.flush();

    m_timer->start(m_period);

    emit changeStatus(m_timer->isActive());
}

void SaveCurveData::stop()
{
    m_timer->stop();
    m_file.close();

    emit changeStatus(m_timer->isActive());
}

bool SaveCurveData::getStatus() const
{
    return m_timer->isActive();
}

void SaveCurveData::save()
{

}

void SaveCurveData::onTimeout()
{
    if (m_datas.isEmpty())
        return;

    if (m_file.isOpen())
    {
        foreach (auto str, m_datas)
        {
            m_file.write(str.toUtf8());
        }
    }
    m_file.flush();
    m_datas.clear();
}
